package com.xhg.mqtt.util;

import com.google.protobuf.ByteString;
import com.xhg.mqtt.dto.MqttMessagePb;

/**
 * proto协议解析工具
 *
 * @author E.T
 * @version 1.0
 * @Description
 * @date 2018-07-18 18:41
 * @updateby
 * @updatedate
 * @since 1.0
 */
public class ProtoBufUtil {


    public static byte[] encode(MqttMessagePb.MqttMessage req) throws Exception {
        return req.toByteArray();
    }

    /**
     * 解析pb消息
     * @param message 消息内容
     * @return
     */
    public static MqttMessagePb.MqttMessage decode(byte[] message) throws Exception {
            return MqttMessagePb.MqttMessage.parseFrom(message);
    }

    /**
     * 构建消息头
     * @param eventCode 指令码
     * @param messageId 消息id
     * @param deviceId 设备码
     * @param version 版本号
     * @param cc 控制码
     * @param resultCode 返回结果码
     * @param resultDesc 返回结果说明
     * @return
     */
    public static MqttMessagePb.MqttHead.Builder builderHead(String eventCode, String messageId, String deviceId, String version,int cc,int resultCode,String resultDesc)  throws Exception{
        MqttMessagePb.MqttHead.Builder builder = MqttMessagePb.MqttHead.newBuilder();
        builder.setEventCode(eventCode);
        builder.setMessageId(messageId);
        builder.setDeviceId(deviceId);
        builder.setVersion(version);
        builder.setResultCode(resultCode);
        if (resultDesc!=null && resultDesc != "") {
            builder.setResultDesc(resultDesc);
        }
        builder.setCc(cc);
        return  builder;
    }

    /**
     * 构建消息主体
     * @param head 消息头
     * @param body 消息体
     * @return
     */
    public static byte[] builderMessage(MqttMessagePb.MqttHead.Builder head, ByteString body)  throws Exception{
        MqttMessagePb.MqttMessage.Builder message = MqttMessagePb.MqttMessage.newBuilder();
        if (null != head) {
            message.setHead(head);
        }
        if (null != body) {
            message.setBody(body);
        }
        return message.build().toByteArray();
    }

    /**
     * 解码头消息
     * @param message
     * @return
     */
    public static MqttMessagePb.MqttHead decodeHead(byte[] message)  throws Exception{
        MqttMessagePb.MqttMessage msg = decode(message);
        return msg.getHead();
    }

}
